<style scoped>
    .management-unit-page{}
    .management-unit-page .condition{line-height: 36px;}


    /* 新建或者修改法人的弹窗 */
    .el-dialog.el-dialog--tiny{width:36%;}
    .el-dialog .el-dialog__body{padding-bottom:0;}
    .el-dialog .el-input{width:66%;}
    .el-dialog .el-dialog__body .el-form-item:last-of-type{margin-bottom:0;}
    .el-dialog .el-form-item__label{text-align: left;}
</style>
<template> 
    <div class="management-unit-page">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" style="border-bottom:1px solid #ccc;">
            <!--法人名称-->
            <el-form-item :label="nowLangue.legalName" class="selectMB10">
                <el-input size="mini" v-model="formInline.name" :placeholder="nowLangue.pleaseImport+nowLangue.legalName"></el-input>
            </el-form-item>
            <!--法人代码-->
            <el-form-item :label="nowLangue.legalCode" class="selectMB10">
                <el-input size="mini" v-model="formInline.code" :placeholder="nowLangue.pleaseImport+nowLangue.legalCode"></el-input>
            </el-form-item>
            <!--当前状态-->
            <el-form-item :label="nowLangue.currStatus" class="selectMB10">
                <el-select size="mini" clearable v-model="formInline.status" :placeholder="nowLangue.pleaseSelect">
                    <el-option :label="nowLangue.enable" value="true"></el-option>
                    <el-option :label="nowLangue.forbidden" value="false"></el-option>
                </el-select>
            </el-form-item>
            <!--查询-->
            <el-form-item class="selectMB10">
                <el-button class="bolder outsideBtnBS selectAll" :disabled="selectDisabled" size="mini" type="danger" @click="handleQuery" v-text="nowLangue.query"></el-button>
            </el-form-item>
        </el-form>
        <!--表格-->
        <!--法人列表：-->
        <label class="default-label" v-text="nowLangue.legalList"></label>
        <!--新增法人按钮-->
        <el-button class="bolder outsideBtnBS" size="mini" type="danger"  @click="handleAdd()" v-if="powerFlag" v-text="nowLangue.addLegal"></el-button>
        <el-table :data="tableData" border style="width: 100%;" v-loading.body="loading" :element-loading-text="nowLangue.loading">
            <!--序-->
            <el-table-column type="index" header-align="center" align="center" :label="nowLangue.xu"  width="40"></el-table-column>
            <!--操作-->
            <el-table-column :label="nowLangue.operate" header-align="center" align="center" width="80" v-if="powerFlag">
                <template scope="scope">
                    <!--修改-->
                    <button class="operationItem bolder" v-if="!scope.row.enabled" @click="handleEdit(scope.$index, scope.row)" v-text="nowLangue.update"></button>
                    <button class="operationItem disabled bolder" v-else-if="scope.row.enabled" v-text="nowLangue.update"></button>
                    <!--启用/禁用-->
                    <button class="operationItem bolder" v-if="!scope.row.enabled" @click="handleOpen(scope.$index, scope.row)" v-text="nowLangue.enable" :disabled="statusDisabled"></button>
                    <button class="operationItem bolder" v-else-if="scope.row.enabled" @click="handleDisable(scope.$index, scope.row)" v-text="nowLangue.forbidden" :disabled="statusDisabled"></button>
                </template>
            </el-table-column>
            <!--法人名称-->
            <el-table-column prop="legalPersonName" :label="nowLangue.legalName" header-align="center" show-overflow-tooltip></el-table-column>
            <!--法人代码-->
            <el-table-column prop="legalPersonCode" :label="nowLangue.legalCode" header-align="center" width="180" show-overflow-tooltip></el-table-column>
            <!--当前状态-->
            <el-table-column prop="enabledName" :label="nowLangue.currStatus" header-align="center" align="center" width="80" show-overflow-tooltip></el-table-column>
        </el-table>
        <!--分页-->
        <el-pagination v-if="isPaging" @size-change="handleSizeChange" @current-change="handleCurrentChange"
                       :current-page="pageIndex"
                       :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
                       :page-count="totalPage" :total="totalNumber">
        </el-pagination>

        <!--新增或者修改法人的弹框-->
        <el-dialog :title="title" size="tiny" :visible.sync="dialogFormVisible" :lock-scroll="false">
            <el-form :model="form" ref="form">
                <!--法人名称：-->
                <el-form-item :label="nowLangue.legalName" prop="name" :rules="[{ required: true, message: nowLangue.pleaseImport+nowLangue.legalName},{ max: 100, message: nowLangue.lessThan100},{ validator: checkName, trigger: 'blur' }]">
                    <el-input size="mini" v-model.trim="form.name" auto-complete="off" :placeholder="nowLangue.pleaseImport+nowLangue.legalName"></el-input>
                </el-form-item>
                <!--法人代码：-->
                <el-form-item :label="nowLangue.legalCode" prop="code" :rules="[{ required: true, message: nowLangue.pleaseImport+nowLangue.legalCode},{max: 20, message: nowLangue.lessThan20},{ validator: checkCode, trigger: 'blur' }]">
                <el-input size="mini" v-model.trim="form.code" auto-complete="off" :placeholder="nowLangue.pleaseImport+nowLangue.legalCode"></el-input>
                </el-form-item>
                <!--状态：-->
                <el-form-item :label="nowLangue.status" prop="status" :rules="[{ required: true, message: nowLangue.pleaseSelect+nowLangue.status}]">
                    <el-radio-group v-model="form.status">
                        <!--启用/禁用-->
                        <el-radio label="true" v-cloak>{{nowLangue.enable}}</el-radio>
                        <el-radio label="false" v-cloak>{{nowLangue.forbidden}}</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <!--返 回-->
                <el-button class="bolder outsideBtnBS" size="mini" @click="dialogFormVisible = false" v-text="nowLangue.return"></el-button>
                <!--保 存-->
                <el-button class="bolder outsideBtnBS " size="mini" type="danger" @click="saveLegalPerson()"  v-text="nowLangue.save" :disabled="saveDisabled"></el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            var _this=this;
            var checkName = (rule, value, callback) => {

                if (!value) {
                    //'法人名称不能为空'
                    var tip1=_this.languageType=="zh"?'法人名称不能为空':'The legal person name cannot be empty';
                    return callback(new Error(tip1));
                }
                setTimeout(() => {
                    //判断是否已经存在
                    var id = _this.form.id;
                    var tmp = {id:id,legalPersonName:value};
                    $.ajax({
                        type: 'POST',
                        async:false,
                        url: _this.metadata_service+"legalPerson/searchIfExist",
                        cache: false,
                        data:JSON.stringify(tmp),
                        dataType:'JSON',
                        contentType: "application/json;charset=utf-8",
                        success: function (data) {
                            //存在时候给友好提示
                            if (!data.success) {
                                callback(new Error(data.errorMessage));
                            }else{
                                callback();
                            }
                        }
                    });
                    callback();
                }, 1000);
            };
            var checkCode = (rule, value, callback) => {
                if (!value) {
                    var tip2=_this.languageType=="zh"?'法人编码不能为空':'The legal person code cannot be empty';
                    return callback(new Error(tip2));
                }
                setTimeout(() => {
                    var re =  /^[0-9a-zA-Z]*$/g;  //判断字符串是否为数字和字母组合
                    if (!re.test(value)){
                        var tip3=_this.languageType=="zh"?'请输入数字或字母组合':'Please enter a combination of numbers or letters';
                        callback(new Error(tip3));
                    } else {
                        //判断是否已经存在
                        var id = _this.form.id==null?"":_this.form.id;
                        var tmp = {id:id,legalPersonCode:value};
                        $.ajax({
                            type: 'POST',
                            async:false,
                            url: _this.metadata_service+"legalPerson/searchIfExist",
                            cache: false,
                            data:JSON.stringify(tmp),
                            dataType:'JSON',
                            contentType: "application/json;charset=utf-8",
                            success: function (data) {
                                //存在时候给友好提示
                                if (!(data.success)) {
                                    callback(new Error(data.errorMessage));
                                }else{
                                    callback();
                                }
                            }
                        });
                        callback();
                    }
                }, 1000);
            };
            return {
                nowLangue:{},
                checkName:checkName,
                checkCode:checkCode,
                pageIndex:1,    //当前页（必传）
                pageSize :10,   //每页多少条
                totalNumber: 20,
                totalPage:2,
                 isPaging:false,
                // 以管理单元为例
                formInline:{
                    id:'',
                    name:'',
                    code:'',
                    status:''
                },
                loading:false,
                // 表格
                tableData: [],
                // 分页
                //  新增或者修改法人的弹窗
                dialogFormVisible: false,
                form: {
                    id:'',
                    name: '',
                    code:'',
                    status:''
                },
                title:"",    // 新增或者修改法人弹窗的title
                powerFlag:false,
                
                selectDisabled:false,//查询禁用
                statusDisabled:false,  //启用禁用操作钮的禁用
                saveDisabled:false  //新增、修改的保存禁用
            };
        },
        computed:{
           powerData(){
               return this.$store.state.powerData;
           },
            languageType(){
                return this.$store.state.languageType;
            }
         },
        created:function(){
            var _this = this;
            _this.languageType=="zh"?_this.nowLangue=_this.language.zh:_this.nowLangue=_this.language.en;
        },
        watch:{
            languageType(){
                this.languageType=="zh"?this.nowLangue=this.language.zh:this.nowLangue=this.language.en;
            },
            powerData(){
                for(var i=0;i<this.powerData.length;i++){
                    if(this.powerData[i]=="ROLE_security_managementUnit_operation"){
                        this.powerFlag=true;
                        break;
                    }
                }
            }
        },
        //进入页面立即运行此方法
        mounted: function () {
           var _this = this;
            //判断权限
            for(var i=0;i<_this.powerData.length;i++){
                if(_this.powerData[i]=="ROLE_security_managementUnit_operation"){
                    _this.powerFlag=true;
                    break;
                }
            }
            // //ajax前后查询按钮禁用
            // $(".selectAll").ajaxStart(function(){
            //     _this.selectDisabled=true;
            // });
            // $(".selectAll").ajaxStop(function(){
            //     _this.selectDisabled=false;
            // });
            _this.handleQuery();
        },
        methods: {
            // 以管理单元为例
            handleQuery(){
                var _this=this;
                _this.loading=true;
                var tmp={legalPersonName: _this.formInline.name, legalPersonCode: _this.formInline.code, enabled: _this.formInline.status, pageIndex: _this.pageIndex, pageSize: _this.pageSize};
                _this.selectDisabled=true;
                $.ajax({
                    type: 'POST',
                    url: _this.metadata_service+"legalPerson/search",
                    cache: false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        if (data.success) {
                            _this.loading=false;
                            _this.tableData=data.data.dataList;
                            _this.isPaging=true;
                            _this.totalPage=data.data.totalPage;
                            _this.totalNumber=data.data.totalNumber;
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }   
                        _this.selectDisabled=false;
                    }
                });
            },
            updateStatus(id, status) {
                var _this=this;
                var tmp={id: id, enabled: status};
                _this.statusDisabled=true;
                $.ajax({
                    type: 'POST',
                    url: _this.metadata_service+"/legalPerson/updateLegalPersonStatus",
                    cache: false,
                    data:JSON.stringify(tmp),
                    dataType:'JSON',
                    contentType: "application/json;charset=utf-8",
                    success: function (data) {
                        if (data.success) {
                            var success=_this.languageType=="zh"?'提交成功！':'Submit successfully!';
                            _this.common.successTip(success);
                            _this.handleQuery();
                        }else{
                            _this.common.errorTip(data.errorMessage);
                        }  
                        _this.statusDisabled=false;                          
                    }
                });
            },
            handleAdd(){
                var _this=this;
                _this.dialogFormVisible = true;
                if(this.$refs['form']) {
                    this.$refs['form'].resetFields();
                }
                _this.form.id = '';
                _this.form.name = '';
                _this.form.code='';
                _this.form.status = 'false';
                _this.title=_this.languageType=="zh"?'新增法人':'Create person';
            },
            saveLegalPerson(){
                var _this=this;
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        //新增
                        var tmp={legalPersonName: _this.form.name, legalPersonCode: _this.form.code, enabled: _this.form.status};
                        var urlPath = _this.metadata_service+"/legalPerson/add";
                        //修改
                        if(_this.form.id!=''){
                            tmp = {id:_this.form.id,legalPersonName: _this.form.name, legalPersonCode: _this.form.code, enabled: _this.form.status};
                            urlPath = _this.metadata_service+"/legalPerson/update";
                        }
                        _this.saveDisabled=true;
                        $.ajax({
                            type: 'POST',
                            url: urlPath,
                            cache: false,
                            data:JSON.stringify(tmp),
                            dataType:'JSON',
                            contentType: "application/json;charset=utf-8",
                            success: function (data) {
                                if (data.success) {
                                    _this.dialogFormVisible=false;
                                    _this.handleQuery();
                                }else
                                    _this.common.errorTip(data.errorMessage);
                                _this.saveDisabled=false;
                            }
                        });
                    } else {
                        var  err=_this.common.formErrorInfo();
                        _this.common.errorTip(err);
                        return false;
                    }
                });

            },
            //   表格(修改法人)
            handleEdit(index, row) {
                 var _this=this;
                 this.dialogFormVisible=true;
                 if(this.$refs['form']) {
                    this.$refs['form'].resetFields();
                 }
                 _this.form.id = row.id;
                 _this.form.name = row.legalPersonName;
                 _this.form.code = row.legalPersonCode;
                _this.title=_this.languageType=="zh"?'修改法人':'Update person';
                 if (row.enabled == false) {
                     _this.form.status ='false';
                 } else {
                     _this.form.status ='true';
                 }
            },
            handleDisable(index, row) {
                var _this=this;
                // console.log("farenid"+row.id);
                $.ajax({
                    type: 'GET',
                    url: _this.metadata_service + "legalPerson/SearchCountEnabledLegalPerson/"+row.id,
                    cache: false,
                    success: function (data) {
                        if (data==0) {
                            _this.updateStatus(row.id, false);
                        } else
                            _this.common.errorTip(_this.nowLangue.legalNoDisableTip);
                            // _this.common.errorTip("该法人不能禁用，法人下有启用的用户");
                    }
                });
            },
            handleOpen(index, row) {
                var _this=this;
                 _this.updateStatus(row.id, true);
             },
            //   分页
            handleSizeChange(val) {
                // console.log(`每页 ${val} 条`);
                var _this=this;
                _this.pageSize=val;
                _this.handleQuery();

            },
            //点击页码分页查询点击事件
            handleCurrentChange(val) {
                // console.log(`当前页: ${val}`);
                var _this=this;
                _this.pageIndex=val;
                _this.handleQuery();
            }
        }
    }
</script>



